from rest_framework.generics import ListAPIView, CreateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from toutiao.models import News,NewsCategory
from rest_framework.filters import OrderingFilter
from rest_framework.views import APIView
from .serializers import NewCategorySerializer, NewsSerializer, NewsListSerializer, submitNewsSerializer


class Newcategory(APIView):
    '''新闻分类视图'''
    #使用视图集返回数据因为是要找到整体新闻头条分类
    def get(self,request):
        queryset = NewsCategory.objects.all()
        serializer = NewCategorySerializer(queryset,many=True)
        return Response(serializer.data)


class NewsListView(ListAPIView):
    '''新闻列表'''
    #使用新闻序列化器
    serializer_class = NewsListSerializer
    filter_backends = (OrderingFilter,)
    #根据创建时间排序达到新闻最新的目的
    ordering_fields = ('create_time')

    def get_queryset(self):
        #根据不同的新闻类别返回不同的
        category_id = self.kwargs['category_id']
        return News.objects.filter(category_id=category_id)


class NewsDetailsView(APIView):
    '''

    :param new_id,contents,create_time,user,category_id,
    :return

        请求新闻详情数据
    '''
    def get(self,request,news_id):

        news = News.objects.get(id=news_id )
        serializer = NewsSerializer(news)

        return Response(serializer.data)


class submitNewsViewSet(CreateAPIView):
    """发布头条"""
    permission_classes = [IsAuthenticated] # 权限验证
    serializer_class = submitNewsSerializer